package cn.flkj.gmca.ca.gmca.gmcautil;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author : 州长在手 2020/12/15 上午8:49
 */
public class FileUtil {

    public static void saveCerFile(String path,String certString){
        String begin = "-----BEGIN CERTIFICATE-----\n";
        String end = "\n-----END CERTIFICATE-----";
        certString = begin + certString + end;
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(path);
            fileOutputStream.write(certString.getBytes());
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void savePriFile(String path,String pri){
        String begin = "-----BEGIN PRIVATE KEY-----\n";

        String end = "\n-----END PRIVATE KEY-----";
        pri = begin + pri + end;

        try {
            FileOutputStream fileOutputStream = new FileOutputStream(path);
            fileOutputStream.write(pri.getBytes());
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static byte[] readCert(String path) throws IOException {
        String begin = "-----BEGIN CERTIFICATE-----\n";
        String end = "\n-----END CERTIFICATE-----";
        FileInputStream fileInputStream = new FileInputStream(path);
        byte[] bytes = new byte[fileInputStream.available()];
        fileInputStream.read(bytes);
        String res = new String(bytes);
        res = res.replace(begin,"");
        res = res.replace(end,"");
        System.out.println(res);
        return res.getBytes();
    }

    public static byte[] readPriKey(String path) throws IOException  {
        String begin = "-----BEGIN PRIVATE KEY-----\n";
        String end = "\n-----END PRIVATE KEY-----";
        FileInputStream fileInputStream = new FileInputStream(path);
        byte[] bytes = new byte[fileInputStream.available()];
        fileInputStream.read(bytes);
        String res = new String(bytes);
        res = res.replace(begin,"");
        res = res.replace(end,"");
        return res.getBytes();
    }


}
